package com.example.client;


import com.example.client.handler.SigninHandler1;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class SigninFrame1 extends JFrame implements ActionListener {

    private JTextField username;
    private JPasswordField password;
    private JButton signinBtn;

    public SigninFrame1() {
        initUI();
    }

    private void initUI() {
        setTitle("用户登录");
        setSize(300, 180);
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        JPanel panel = new JPanel(new BorderLayout(10, 10));
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        JPanel inputPanel = new JPanel(new GridLayout(2, 2, 5, 5));
        username = new JTextField("");
        password = new JPasswordField("");

        inputPanel.add(new JLabel("用户名:"));
        inputPanel.add(username);
        inputPanel.add(new JLabel("密码:"));
        inputPanel.add(password);

        signinBtn = new JButton("登录");
        signinBtn.addActionListener(this);
        signinBtn.setActionCommand("signin");

        panel.add(inputPanel, BorderLayout.CENTER);
        panel.add(signinBtn, BorderLayout.SOUTH);

        add(panel);

        setLocationRelativeTo(null);
        setVisible(true);
    }

    private void signin() {
        String username = this.username.getText();
        char[] password = this.password.getPassword();

        if (username.isEmpty() || password.length == 0) {
            JOptionPane.showMessageDialog(this, "用户名或密码不能为空", "输入错误", JOptionPane.WARNING_MESSAGE);
            return;
        }

        SigninHandler1 signinHandler1 = new SigninHandler1(username, new String(password));
        Thread signinThd = new Thread(signinHandler1);
        this.setVisible(false);
        signinThd.start();

        try {
            signinThd.join();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getActionCommand().equals("signin")) {
            signin();
        }
    }

    public static void main(String[] args) {
        new SigninFrame1();
    }
}